package com.cybertron.ironhide.manage.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import com.cybertron.ironhide.manage.common.Constants;
import com.cybertron.ironhide.manage.common.base.Pager;
import com.cybertron.ironhide.manage.domain.Tag;
import com.cybertron.ironhide.manage.domain.TagValue;
import com.cybertron.ironhide.manage.persistence.CategoryMapper;
import com.cybertron.ironhide.manage.persistence.TagMapper;
import com.cybertron.ironhide.manage.persistence.TagValueMapper;
import com.cybertron.ironhide.manage.service.TagService;
import com.cybertron.ironhide.manage.util.CommonUtil;

@Service
public class TagServiceImpl implements TagService {

	@Resource
	private TagMapper tagMapper;

	@Resource
	private TagValueMapper tagValueMapper;

	@Resource
	private CategoryMapper categoryMapper;

	@Override
	public List<Tag> selectBySelective(Tag tag, Pager pager) {
		return tagMapper.selectBySelective(tag, pager);
	}

	@Override
	public void insertSelective(Tag record) {
		record.setId(CommonUtil.getUUID());
		record.setCreateDate(new Date());
		tagMapper.insertSelective(record);
		List<TagValue> values = record.getValues();
		if (values != null && values.size() != 0) {
			for (TagValue tagValue : values) {
				tagValue.setId(CommonUtil.getUUID());
				tagValue.setTagId(record.getId());
				tagValueMapper.insertSelective(tagValue);
			}
		}
	}

	@Override
	public Tag selectByPrimaryKey(String id) {
		return tagMapper.selectByPrimaryKey(id);
	}

	@Override
	public void updateByPrimaryKeySelective(Tag record) {
		tagValueMapper.deleteByTagId(record.getId());
		tagMapper.updateByPrimaryKeySelective(record);
		List<TagValue> values = record.getValues();
		if (values != null && values.size() != 0) {
			for (TagValue tagValue : values) {
				tagValue.setId(CommonUtil.getUUID());
				tagValue.setTagId(record.getId());
				tagValueMapper.insertSelective(tagValue);
			}
		}
	}

	@Override
	public void deleteByPrimaryKey(String id) {
		tagMapper.deleteByPrimaryKey(id);
		tagValueMapper.deleteByTagId(id);
	}

	@Override
	public void insertSelective(Tag tag, File tagFile) {
		Workbook workbook = null;
		try {
			workbook = new XSSFWorkbook(new FileInputStream(tagFile));
		} catch (Exception ex) {
			try {
				workbook = new HSSFWorkbook(new FileInputStream(tagFile));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (workbook == null) {
			return;
		}
		for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
			Sheet sheet = workbook.getSheetAt(numSheet);
			if (sheet == null) {
				continue;
			}
			String secondCateId = null;
			for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
				Row row = sheet.getRow(rowNum);
				if (row != null && row.getCell(0) != null) {
					Cell cellTitle = row.getCell(0);
					cellTitle.setCellType(Cell.CELL_TYPE_STRING);
					if (StringUtils.isNotBlank(StringUtils.trim(cellTitle
							.getStringCellValue()))) {
						secondCateId = categoryMapper
								.selectIdByTitle(StringUtils.trim(cellTitle
										.getStringCellValue()));
					}

				}
				if (row == null || row.getCell(1) == null) {
					continue;
				}
				Cell cellCateTitle = row.getCell(1);
				String cateTitle = null;
				cellCateTitle.setCellType(Cell.CELL_TYPE_STRING);
				cateTitle = StringUtils
						.trim(cellCateTitle.getStringCellValue());
				if (StringUtils.isBlank(cateTitle)) {
					continue;
				}
				String categoryId = categoryMapper.selectIdByParentId(
						secondCateId, cateTitle);
				if (StringUtils.isBlank(categoryId)) {
					continue;
				}
				String tagId = tagMapper.selectIdByTitleAndCategoryId(
						tag.getTitle(), categoryId);
				if (StringUtils.isBlank(tagId)) {
					tag.setId(CommonUtil.getUUID());
					tag.setCreateDate(new Date());
					tag.setCategoryId(categoryId);
					tagMapper.insertSelective(tag);
					tagId = tag.getId();
				}
				for (int cellNum = 2; cellNum <= row.getLastCellNum(); cellNum++) {
					Cell cell = row.getCell(cellNum);
					if (cell == null) {
						continue;
					}
					cell.setCellType(Cell.CELL_TYPE_STRING);
					String val = cell.getStringCellValue();
					if (StringUtils.isBlank(val)) {
						continue;
					}
					val = StringUtils.trim(val.replace(
							String.valueOf((char) 160), ""));
					TagValue tagValue = tagValueMapper.selectByTagIdAndVal(
							tagId, val);
					if (tagValue == null) {
						tagValue = new TagValue();
						tagValue.setId(CommonUtil.getUUID());
						tagValue.setVal(val);
						tagValue.setTagId(tagId);
						tagValue.setCreateDate(new Date());
						tagValueMapper.insertSelective(tagValue);
					} else {
						tagValue.setVal(val);
						tagValue.setTagId(tagId);
						tagValue.setModifyDate(new Date());
						tagValueMapper.updateByPrimaryKey(tagValue);
					}
				}
			}
		}
	}

	@Override
	public void buildTag() {
		List<TagValue> tagValues = tagValueMapper.selectAll();
		List<String> lines = null;
		File tagFile = null;
		if (tagValues != null && tagValues.size() > 0) {
			lines = new ArrayList<String>();
			tagFile = new File(Constants.TAG_PATH);
			File tagParentFile = tagFile.getParentFile();
			if (!tagParentFile.exists()) {
				tagParentFile.mkdirs();
			}
			for (TagValue tagValue : tagValues) {
				String line = tagValue.getVal() + "=>" + tagValue.getId()
						+ "=>" + tagValue.getCategoryId();
				lines.add(line);
			}
			try {
				FileUtils.writeLines(tagFile, "UTF-8", lines);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
